#!/bin/bash
sudo mkdir -p /opt/wlou
sudo mkdir -p /opt/wlou/tools
sudo mkdir -p /opt/wlou/pyenv
sudo cp -rf ./init.sql /opt/wlou/init.sql
sudo cp -rf ./start.sh /opt/wlou/start.sh
sudo cp -rf ./app /opt/wlou/app
sudo chmod 777 /tmp
sudo rm -rf /var/lib/apt/lists/* 
sudo mkdir -p /opt/wlou/model
sudo mkdir -p /opt/wlou/sandbox/python-packages
sudo chmod 755 /opt/wlou/start.sh
sudo useradd --no-create-home --home /opt/wlou/sandbox sandbox -g root
sudo chown -R sandbox:root /opt/wlou/sandbox
sudo chmod g-x /usr/local/bin/* /usr/bin/* /bin/* /usr/sbin/* /sbin/*
sudo chmod g+x /bin/sh

sudo apt update
sudo apt install -y --no-install-recommends make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
sudo apt install -y --no-install-recommends libgl1 libglx-mesa0 libglib2.0-0 libglib2.0-dev ffmpeg
version=$(python3 --version | awk '{print $2}')
old=$(python3 --version | awk '{print $2}' | awk -F. '{print $1$2}')
v="3.11.11"
new="311"
# 使用Python代码获取并比较版本号
if [ $old -lt $new ]; then
    echo "当前Python版本小于3.11，开始升级Python..."
    git clone https://gitee.com/bidcms/pyenv.git ~/.pyenv
    echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
    echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
    echo 'eval "$(pyenv init --path)"' >> ~/.bashrc
    echo 'eval "$(pyenv init -)"' >> ~/.bashrc
    . ~/.bashrc
    wget https://mirrors.huaweicloud.com/python/${v}/Python-${v}.tar.xz -P ~/.pyenv/cache/;
    pyenv install ${v}
    pyenv global ${v}
    pyenv shell ${v}
    version="3.11.11"
else
    echo "当前版本无需升级"
fi
sudo apt clean all
cd /opt/wlou/app
# 通过 heredoc 写入多行内容
sudo tee -a /etc/profile << EOF
# Wlou Custom Environment Variables
export WLOU_VERSION="v1.0.0 (build at wlou, commit: 1.0.0)"
export WLOU_CONFIG_TYPE=FILE
export LANG=en_US.UTF-8
export POSTGRES_MAX_CONNECTIONS=1000
export HF_ENDPOINT=https://hf-mirror.com
EOF
. /etc/profile
sudo apt install -y python3-pip python3-venv
python3 -m venv /opt/wlou/pyenv
. /opt/wlou/pyenv/bin/activate
pip install --upgrade pip
# pip install virtualenv && virtualenv /opt/wlou/pyenv
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install -r requirements.txt
#if [ "$(uname -m)" = "x86_64" ]; then sed -i 's/^torch.*/torch = {version = "^2.2.1+cpu", source = "pytorch"}/g' pyproject.toml; fi
# pip install poetry==1.8.5 --break-system-packages
# poetry config virtualenvs.create false
# poetry env use ${version}
# poetry install --no-root
# poetry shell